package com.yuushya.utils.controller

import ch.qos.logback.core.util.FileUtil
import com.yuushya.datagen.ZipReader
import com.yuushya.ui.Mode
import com.yuushya.utils.FileUtils
import com.yuushya.utils.ImageSizeReader
import jakarta.servlet.http.HttpServletResponse
import org.apache.tomcat.util.http.fileupload.IOUtils
import org.springframework.http.MediaType
import org.springframework.util.FileSystemUtils
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.net.URLEncoder
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.LinkedBlockingQueue
import kotlin.io.path.exists

@RestController
@RequestMapping("/api")
class ImageSizeChecker(
    // @Value("\${config.uploadPath}") val uploadPath:String
){

    @PostMapping("/image-size-checker/upload")
    fun upload(
        @RequestPart file: MultipartFile,
        response: HttpServletResponse
    ){

        //获取文件全名
        val fileName = file.originalFilename?:"temp"
        //文件上传路径对象
        val uploadFolder = Files.createTempDirectory("temp")
        //压缩包存储目标文件对象
        val destPath = uploadFolder.resolve("./$fileName");

        //步骤1、把上传的压缩包文件保存到指定压缩包路径
        file.transferTo(destPath)

        //解压目标文件夹对象（压缩文件解压到此文件夹中）
        val extractFolder =  uploadFolder.resolve("./extract").also {
            //判断解压后文件夹是否存在//不存在就创建
            if(!it.exists())  Files.createDirectory(it)
        };


        val zipReader= ZipReader(destPath, extractFolder)
        zipReader.unzip()

        Mode.imageSize = Mode.registerTableType("image")
        val imageSizeReader= ImageSizeReader(extractFolder)
        imageSizeReader.readAllPng()
        val tableFileName = "image${SimpleDateFormat("yyyyMMddHHmmss").format(Date())}.prn"
        val downloadFileName = URLEncoder.encode(tableFileName, "UTF-8")
        val outputPath =uploadFolder.resolve("./$tableFileName")
        Files.writeString(outputPath, Mode.imageSize.joinToString("\n"))
        // 设置文件下载方式：附件下载
        response.setHeader("Content-Disposition", "attachment;fileName=$downloadFileName");
        response.addHeader("resource-filename", downloadFileName)
        response.setHeader("Access-Control-Expose-Headers","resource-filename");
        response.contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        val outputStream = response.outputStream
        val inputStream = Files.newInputStream(outputPath)
        IOUtils.copy(inputStream,  response.outputStream)
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
        Dustbin.throwJunk(uploadFolder)
        //FileUtils.deleteAll(extractFolder)

    }




}